package com.qf.controller;


import com.qf.captcha.CaptchaCodeManager;
import com.qf.pojo.DtsAdmin;
import com.qf.shiro.AdminAuthorizingRealm;
import com.qf.util.*;
import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.apache.shiro.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

@RestController//
@RequestMapping("/admin/auth")
@CrossOrigin
@Slf4j
public class AdminAuthController {

    /**
     * 验证码
     *
     * {
     *     "errno":0,
     *  	"data":	{
     *         "img":"/9j/4AAQSkZJRlZ/2Q==",//验证码图片
     *         "uuid":"b5ca22d8b9e14a88b2851da906d19e4f"  UUID
     *     },
     *     "errmsg":"成功"
     * }
     */
    @GetMapping("/capthaImage")
    public Object captchaImage() throws Exception{
        //1.验证码
        String code= VerifyCodeUtils.generateVerifyCode(4);
        //2.uuid
        String uuid = UUID.randomUUID(true).toString();//true : uuid工具包
        //验证码图片
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        VerifyCodeUtils.outputImage(111,36,outputStream,code);
        //4:验证码保存在Session中 UUID就是缓存的key值
        CaptchaCodeManager.addToCache(uuid,code,null);//默认3分钟
        Map<String ,Object> result=new HashMap<>();
        result.put("img", Base64.encode(outputStream.toByteArray()));
        result.put("uuid",uuid);
        return ResponseUtil.ok(result);
    }

    /**
     * 提交登录
     * 上
     *{
     * 	"code": "66e8",
     * 	"password": "123456",
     * 	"username": "qianfeng",
     * 	"uuid": "cab317c6-1bf1-436d-96ac-fda9f8d37dde"
     * }
     *下
     * {
     *     "errno":0,
     *  	"data":"568f6dd8-97c7-450d-a00b-0a01c3b930c7", //是当前用户Session的ID
     *  	"errmsg":"成功"
     * }
     */

    @PostMapping("/login")
    public Object login(@RequestBody String body){
        //验证码
        String code = JacksonUtil.parseString(body, "code");
        String username = JacksonUtil.parseString(body, "username");
        String password = JacksonUtil.parseString(body, "password");
        String uuid = JacksonUtil.parseString(body, "uuid");

        //1.验证码是否正确
        String cachedCaptcha = CaptchaCodeManager.getCachedCaptcha(uuid);
   /*     if (StringUtils.isEmpty(cachedCaptcha)){
            log.error("【登录】发生错误：{}",AdminResponseCode.AUTH_CAPTCHA_EXPIRED.desc());
            //return ResponseUtil.fail(1,"验证码失效");//正式项目 硬编码问题
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
        }
        if (!cachedCaptcha.equalsIgnoreCase(code)){
            log.error("【登录】发生错误：{}",AdminResponseCode.AUTH_CAPTCHA_ERROR.desc());
            return AdminResponseUtil.fail(AdminResponseCode.AUTH_CAPTCHA_ERROR);
        }       */
        //2:开始校验用户名密码是否正确
        Subject subject = SecurityUtils.getSubject();

        Md5Hash md5Hash=new Md5Hash(password,username,1024);

        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username,md5Hash.toString());
        //开始登录
        try{
            subject.login(usernamePasswordToken);
        }catch (AuthenticationException e){
            log.error("【登录】发生错误: {}",AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD.desc());
            return  AdminResponseUtil.fail(AdminResponseCode.ADMIN_INVALID_ACCOUNT_OR_PASSWORD);
        }

        Session session = subject.getSession();
        //登录成功了  sessionId
        return ResponseUtil.ok(session.getId());
    }

    /**
     * 登录后获取用户名, 角色, 权限详细信息地址
     * {
     *     "errno":0,
     *     "data":{
     *         "roles":["超级管理员"],
     *         "name":"qianfeng",
     *         "perms":["*"],
     *         "avatar":"https://dss1.bdstatic.com/6OF1,499686101&fm=85&app=79&f=JPEG?w=121&h=75&s=81B24C32D40"
     *     },
     *     "errmsg":"成功"
     * }
     */

    @GetMapping("/info")
    public Object info(){
        Subject subject = SecurityUtils.getSubject();
        DtsAdmin dtsAdmin = (DtsAdmin) subject.getPrincipal();
        Map<String,Object> result = new HashMap<>();
        result.put("roles", "[\"超级管理员\"]");
        result.put("name", dtsAdmin.getUsername());
        result.put("perms","[\"*\"]");
        result.put("avatsr",dtsAdmin.getAvatar());
        return ResponseUtil.ok(result);
    }


    public static void main(String[] args) {
        Md5Hash md5Hash = new Md5Hash("123456","qianfeng",1024);
        System.out.println(md5Hash.toString());
    }
}














